package com.xy.tianyu.module.video.activity

import androidx.lifecycle.rxLifeScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.GSYVideoHelper
import com.xy.tianyu.BaseActivity
import com.xy.tianyu.R
import com.xy.tianyu.module.video.adapter.VideoListAdapter
import com.xy.tianyu.module.video.bean.Re
import com.xy.tianyu.module.video.bean.VideoListBean
import com.xy.tianyu.network.Api
import com.xy.tianyu.network.ApiParams
import com.xy.tianyu.utils.TimeUtils
import kotlinx.android.synthetic.main.activity_video.*
import rxhttp.RxHttp
import rxhttp.toClass

class VideoActivity : BaseActivity() {
    private var pageNum = 1
    private val pageSize = 5
    var gsyVideoHelper: GSYVideoHelper? = null
    var gsyVideoBuilder: GSYVideoHelper.GSYVideoHelperBuilder? = null
    var lastVisibleItem = 0

    var firstVisibleItem = 0
    private var newTime = "0"
    private var oldTime = "0"
    private lateinit var videoListAdapter:VideoListAdapter
    private  var videoReList:MutableList<Re> = mutableListOf()
    private var isLoadData = false
    private lateinit var manager: LinearLayoutManager
    private var isRefresh = false

    override fun getLayoutId(): Int {
        return R.layout.activity_video
    }


    private suspend fun getVideoList(): VideoListBean {
        return RxHttp.get(Api.THREE_HUNDRED_AND_SIXTY_VIDEO_BASE_URL)
            .addAll(ApiParams.getVideoListParams(newTime,oldTime,"video",pageNum,pageSize))
            .toClass<VideoListBean>()
            .await()
    }

    override fun initData() {
        tv_video_title.setOnClickListener {
            finish()
        }

        smart_video.setOnRefreshListener {
            newTime = "0"
            oldTime = "0"
            pageNum = 1
            isRefresh = true
            loadVideoData()
        }
        smart_video.setOnLoadMoreListener {
            newTime = TimeUtils.getCurrentTimeStr()
            isRefresh = false
            loadVideoData()
        }
        //创建小窗口帮助类
        gsyVideoHelper = GSYVideoHelper(this)

        //配置
        gsyVideoBuilder = GSYVideoHelper.GSYVideoHelperBuilder()
        gsyVideoBuilder!!
            .setHideStatusBar(true)
            .setNeedLockFull(true)
            .setCacheWithPlay(true)
            .setShowFullAnimation(false)
            .setRotateViewAuto(false)
            .setLockLand(true)
            .setVideoAllCallBack(object : GSYSampleCallBack() {

                override fun onQuitSmallWidget(
                    url: String,
                    vararg objects: Any
                ) {
                    super.onQuitSmallWidget(url, *objects)

                    //大于0说明有播放,//对应的播放列表TAG
                    if (gsyVideoHelper!!.playPosition >= 0 && gsyVideoHelper!!.playTAG == VideoListAdapter.TAG) {
                        //当前播放的位置
                        val position = gsyVideoHelper!!.playPosition
                        //不可视的是时候
                        if (position < firstVisibleItem || position > lastVisibleItem) {
                            //释放掉视频
                            gsyVideoHelper!!.releaseVideoPlayer()
                            videoListAdapter.notifyDataSetChanged()
                        }
                    }
                }
            })

        gsyVideoHelper!!.setGsyVideoOptionBuilder(gsyVideoBuilder)

        manager = LinearLayoutManager(this)
        ry_video_list.layoutManager = manager
        videoListAdapter = VideoListAdapter(R.layout.item_video_list,videoReList,
            false, gsyVideoHelper!!, gsyVideoBuilder!!
        )
        ry_video_list.adapter = videoListAdapter

        ry_video_list.addOnScrollListener(object : RecyclerView.OnScrollListener(){

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                firstVisibleItem = manager.findFirstVisibleItemPosition()
                lastVisibleItem = manager.findLastVisibleItemPosition()
                LogUtils.e("firstVisibleItem $firstVisibleItem lastVisibleItem $lastVisibleItem playPosition ${gsyVideoHelper!!.playPosition} playTag ${gsyVideoHelper!!.playTAG}")
                //大于0说明有播放
                if (gsyVideoHelper!!.playPosition >= 0) {
                    //当前播放的位置
                    val position = gsyVideoHelper!!.playPosition
                    //对应的播放列表TAG
                    if (gsyVideoHelper!!.playTAG == VideoListAdapter.TAG && (position < firstVisibleItem || position > lastVisibleItem)
                    ) {
                        GSYVideoManager.releaseAllVideos()
                        videoListAdapter.notifyItemChanged(position)
                    }
                }
            }
        })
        loadVideoData()
    }


    private fun loadVideoData(){
        rxLifeScope.launch ({
            val videoListBean = getVideoList()
            val list = videoListBean.data.res
            if (list.isNotEmpty()){
                pageNum++
                oldTime = TimeUtils.getCurrentTimeStr()
                if (isRefresh){
                    videoReList.clear()
                }
                videoReList.addAll(list)
                videoListAdapter.notifyDataSetChanged()
            }
        },{
            ToastUtils.showShort(it.message)
        },{

        },{
            smart_video.finishRefresh()
            smart_video.finishLoadMore()
        })
    }

    override fun onBackPressed() {
        if (gsyVideoHelper!!.backFromFull()){
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }


    override fun onDestroy() {
        super.onDestroy()
        gsyVideoHelper!!.releaseVideoPlayer()
        GSYVideoManager.releaseAllVideos()
    }
}